<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2025/3/23
 * 描述:
 */

namespace app\result\admin;

use app\model\admin\Admin;
use app\model\admin\AdminMenu;
use app\model\auto\RoleAuths;
use app\result\BaseResult;

class MenusResult extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new AdminMenu();
    }

    //我的菜单列表,todo 根据权限获取
    public function my_list($admin_id)
    {
        $role_id = (new Admin())->get_value(['admin_id' => $admin_id], 'role_id');
        if ($role_id == 0) {
            $data = (new AdminMenu())->data_list_nopage([], '*', 'sort desc, id asc');
        } else {
            $data = (new RoleAuths())->alias('a')
                ->join('admin_menu b', 'a.menu_id=b.id', 'left')
                ->where('a.role_id', $role_id)
                ->where('b.type', 0)
                ->where('b.hidden', 0)
                ->order('b.sort desc, b.id asc')
                ->field('b.*')
                ->select()
                ->toArray();
        }
        if ($data) {
            foreach ($data as &$v) {
                $v['meta'] = [
                    'title' => $v['title'],
                    'icon' => $v['icon'],
                ];
                $v['hidden'] = boolval($v['hidden']);
            }
            $data = getTree($data, 'id', 'parent_id', 'children');

            return self::success_return('success', [
                'routes' => $data,
            ]);
        }
        return self::error_return('error', [
            'routes' => [],
        ]);
    }

    public function save_data($args): array
    {
        $type = intval($args['type'] ?? 0);//0=菜单-页面，1=功能-权限
        $id = intval($args['id'] ?? 0);
        if (empty($args['title'])) {
            return $this->error_return('菜单名称不能为空');
        }
        if (empty($args['path'])) {
            return $this->error_return('菜单路由不能为空');
        }
        if ($type == 1) {
            if (empty($args['parent_id'])) {
                return $this->error_return('请选择所属菜单');
            }
            $parent = $this->model->data_get(['id' => $args['parent_id']]);
            if (!$parent) {
                return $this->error_return('所属菜单不存在');
            }
            $args['hidden'] = 1;
            $args['name'] = $args['title'];
            $args['redirect'] = $parent['redirect'];
            $args['component'] = $parent['component'];
            $args['sort'] = $parent['sort'];
            $args['icon'] = $parent['icon'];
        } else {
            if (empty($args['name'])) {
                return $this->error_return('组件名称不能为空');
            }
        }


        if ($id) {
            $data = $this->model->data_get(['id' => $id]);
            if (!$data) {
                return $this->error_return('数据不存在');
            }
        }

        $baseData = [
            'type' => $type,
            'parent_id' => intval($args['parent_id'] ?? 0),
            'path' => $args['path'],
            'name' => $args['name'],
            'component' => $args['component'] ?? '',
            'redirect' => $args['redirect'] ?? '',
            'title' => $args['title'],
            'icon' => $args['icon'] ?? '',
            'hidden' => intval($args['hidden'] ?? 0),
            'sort' => intval($args['sort'] ?? 0),
        ];
        if ($id) {
            $res = $this->model->data_update(['id' => $id], $baseData);
            if (!$res) {
                return $this->success_return('菜单未修改');
            }
        } else {
            //去重
            if ($this->model->get_value([
                'type' => $type,
                'parent_id' => intval($args['parent_id'] ?? 0),
                'path' => $args['path'],
                //'name' => $args['name'],
                'component' => $args['component'] ?? '',
                'redirect' => $args['redirect'] ?? '',
                'title' => $args['title'],
            ], 'id')) {
                return $this->error_return('已存在，请勿重复添加');
            }
            $res = $this->model->data_add($baseData);
            if (!$res) {
                return $this->error_return('保存失败');
            }
        }
        admin_log('操作管理员菜单', $args);
        return $this->success_return('保存成功');
    }

    //快速添加
    public function quick_add($args)
    {
        //去重
        if ($this->model->get_value([
            'type' => $args['type'],
            'parent_id' => intval($args['parent_id'] ?? 0),
            'path' => $args['path'],
            //'name' => $args['name'],
            'component' => $args['component'] ?? '',
            'redirect' => $args['redirect'] ?? '',
            'title' => $args['title'],
        ], 'id')) {
            return $this->error_return('已存在，请勿重复添加');
        }
        $res = $this->model->data_add($args);
        if (!$res) {
            return $this->error_return('保存失败');
        }
        admin_log('操作管理员菜单', $args);
        return $this->success_return('保存成功', ['id' => $res]);
    }


    public function list($args = []): array
    {
        $keyword = $args['keyword'] ?? '';
        $parent_id = intval($args['parent_id'] ?? 0);
        $getChild = intval($args['getChild'] ?? 0);
        $where = [];
        if ($keyword) {
            $where['name|title|path'] = ['like', '%' . $keyword . '%'];
        }

        if ($parent_id) {
            $where['parent_id'] = $parent_id;
        }
        $model = $this->model;
        if ($getChild) {
            $total = $this->model->data_count($where);
            $data = $this->model->data_list_nopage($where, '*', 'sort desc,id asc');
            if ($data) {
                foreach ($data as &$value) {
                    $value['is_category'] = false;
                    $value['uniqid'] = get_random(32, true);
                    $value['hasChildren'] = boolval($model->data_count(['parent_id' => $value['id']]));
                    $value['icon_type'] = str_contains($value['icon'], 'el-icon') ? 'el' : 'svg';
                    $value['children'] = [];
                }
                unset($value);
            }
            return $this->success_return('success', [
                'total' => $total,
                'list' => $data
            ]);
        }


        $whereAll = [['parent_id', '=', 0]];
        if ($keyword) {
            $whereAll[] = ['name|title|path', 'like', '%' . $keyword . '%'];
        }
        $data = $model->data_list_nopage($whereAll);

        foreach ($data as &$value) {
            $value['is_category'] = true;
            $value['uniqid'] = get_random(32, true);
            $value['hasChildren'] = $model->data_count(['parent_id' => $value['id']]) > 0;
            $value['icon_type'] = str_contains($value['icon'], 'el-icon') ? 'el' : 'svg';
        }
        unset($value);


        return $this->success_return('success', [
            'data' => $data,
            'total' => count($data)
        ]);
    }

    public function get($args = []): array
    {
        $id = intval($args['id'] ?? 0);
        $data = $this->model->data_get(['id' => $id]);
        if (!$data) {
            return $this->error_return('数据不存在');
        }
        $data['parent_name'] = $this->model->get_value(['id' => $data['parent_id']], 'title') ?? '';
        return $this->success_return('success', [
            'info' => $data,
        ]);
    }


    public function copy($args): array
    {
        $id = intval($args['id'] ?? 0);
        if (!$id) {
            return $this->error_return('参数错误');
        }
        $data = $this->model->data_get(['id' => $id]);
        if (!$data) {
            return $this->error_return('数据不存在');
        }
        $data['title'] = $data['title'] . '_copy';
        unset($data['id']);
        $res = $this->model->data_add($data);
        if (!$res) {
            return $this->error_return('复制失败');
        }
        admin_log('复制菜单', $args);
        return $this->success_return('复制成功');
    }

    public function del_data($args): array
    {
        $id = $args['id'] ?? [];
        if (!$id) {
            return $this->error_return('请选择数据');
        }
        $data = $this->model->data_get(['id' => $id], '*')?->toArray();
        if (!$data) {
            return $this->error_return('数据不存在');
        }
        $sub_data = $this->model->data_list(['parent_id' => $id], 'id')?->toArray();
        //删除子级菜单
        if ($sub_data) {
            $sub_ids = array_column($sub_data, 'id');
            $third_data = $this->model->data_list(['parent_id' => $sub_ids], 'id')?->toArray();
            if ($third_data) {
                $third_ids = array_column($third_data, 'id');
                $this->model->where([['id', 'in', $third_ids]])->delete();
            }
            $this->model->where([['id', 'in', $sub_ids]])->delete();
        }

        $res = $this->model->data_del(['id' => $id]);
        if (!$res) {
            return $this->error_return('删除失败');
        }
        admin_log('删除菜单数据', $data);
        return $this->success_return('删除成功');
    }

    public function list_options($args = [])
    {
        $all = $this->model->data_list_nopage([
            //'hidden' => 0
            'type' => 0
        ], 'id,title as label,id as value,parent_id');
        if ($all) {
            $all = getTree($all, 'id', 'parent_id');
        }
        return self::success_return('success', [
            'list' => $all,
        ]);
    }
}
